package com.loan.controller;

import com.loan.entity.Product;
import com.loan.service.ProductService;
import com.loan.utils.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author z
 */
@RestController
@RequestMapping("/product")
@Slf4j
@Api(tags = "产品管理")
public class ProductController {
    @Resource
    private ProductService productService;

    /**
     * 查询所有产品信息
     */
    @ApiOperation(value = "所有产品信息", httpMethod = "GET", notes = "返回所有产品信息")
    @GetMapping("/list")
    public ResponseResult<List<Product>> findAllProduct() {
        List<Product> allProduct = productService.findAllProduct();
        return ResponseResult.success(allProduct);
    }


    /**
     * 根据id查询产品信息
     */
    @ApiOperation(value = "根据id查询产品信息", httpMethod = "GET", notes = "根据id返回产品信息")
    @GetMapping("/find/{pid}")
    public ResponseResult<Product> findProductById(@PathVariable String pid) {
        Product product = productService.findProductById(pid);
        return ResponseResult.success(product);
    }

    /**
     * <----->测试事务：增加产品
     */
    @ApiOperation(value = "测试事务：添加产品信息", httpMethod = "POST")
    @PostMapping("/add")
    public ResponseResult<Product> addProduct(Product product) {
        productService.insertProduct(product);
        return ResponseResult.success("添加产品成功");
    }

    /**
     * <----->测试事务：删除产品
     */
    @ApiOperation(value = "测试事务：删除产品信息", httpMethod = "DELETE")
    @DeleteMapping("/delete/{pid}")
    @Transactional
    public ResponseResult<Product> deleteProductById(@PathVariable String pid) {
        productService.deleteProduct(pid);
        try {
            int i = 1 / 0;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ResponseResult.success("删除产品成功");
    }
}
